from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.views import APIView
from django.http import Http404
from shopping.models import Cart
from shopping.serializers import CartSerializer
from django.contrib.auth.models import User
from django.db import transaction
from rest_framework.authentication import TokenAuthentication



class CartView(APIView):
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]
    # permission_classes = [AllowAny]

    def get_object(self, pk):
        """获取单个对象"""
        try:
            # pk 即主键，默认状态下就是 id
            return Cart.objects.get(pk=pk)
        except:
            raise Http404

    def get(self, request):
        try:
            user = User.objects.get(pk=request.user)
            serializer = CartSerializer(user.carts.all(), many=True)
            return Response(serializer.data)
        except user.DoesNotExist:
            return Response({"error": "类型查询失败"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @transaction.atomic
    def post(self, request):
        params = request.data
        fid = params.get("pk", None)
        if not fid:
            return Response({"error": "缺少指定参数"}, status=status.HTTP_400_BAD_REQUEST)
        try:
            cart = Cart.objects.create(
                fid=fid,
                user=request.user,
            )
            cart.save()
        except cart.DoesNotExist:
            transaction.rollback()
            return Response({"error": "添加购物车失败"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class CartDeleteView(APIView):
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]
    # permission_classes = [AllowAny]

    @transaction.atomic
    def post(self, request):
        params = request.data
        cid = params.get("pk", None)
        if not cid:
            return Response({"error": "缺少指定参数"}, status=status.HTTP_400_BAD_REQUEST)
        try:
            cart = Cart.objects.filter(
                user=request.user,
                pk=cid,
            ).first()
            cart.delete()
        except cart.DoesNotExist:
            transaction.rollback()
            return Response({"error": "删除购物车商品失败"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
